package staff

import (
	"duoke/model"
	"duoke/service"
	"duoke/tables"
	"duoke/utils/orm"
	"duoke/utils/response"
	"github.com/gin-gonic/gin"
)

var Behavior = new(behaviorCtl)

type behaviorCtl struct{}

func (ctl *behaviorCtl) List(c *gin.Context) {
	staffR, _ := service.Request.Staff(c)
	var req model.ReqList
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	list := make([]tables.Behavior, 0)
	query := orm.Db.Where("goods_id =? AND staff_id =? AND user_id =?", staffR.GoodsId, staffR.Id, req.UserId).Desc("id")
	err := query.Find(&list)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	share_app_message_num, _ := orm.Db.Where("goods_id =? AND staff_id =? AND user_id =? AND action='share_app_message'", staffR.GoodsId, staffR.Id, req.UserId).Count(new(tables.Behavior))
	share_timeline, _ := orm.Db.Where("goods_id =? AND staff_id =? AND user_id =? AND action='share_timeline'", staffR.GoodsId, staffR.Id, req.UserId).Count(new(tables.Behavior))
	favorites, _ := orm.Db.Where("goods_id =? AND staff_id =? AND user_id =? AND action='favorites'", staffR.GoodsId, staffR.Id, req.UserId).Count(new(tables.Behavior))
	view_time, _ := orm.Db.Where("goods_id =? AND staff_id =? AND user_id =? AND action='view'", staffR.GoodsId, staffR.Id, req.UserId).Sum(new(tables.Behavior), "view_time")
	beha := new(tables.Behavior)
	_, _ = orm.Db.Where("goods_id =? AND staff_id =? AND user_id =? AND action='view'", staffR.GoodsId, staffR.Id, req.UserId).Desc("view_percentage").Get(beha)
	response.Success(c, "", gin.H{
		"list":                  list,
		"share_app_message_num": share_app_message_num,
		"share_timeline":        share_timeline,
		"favorites":             favorites,
		"view_percentage":       beha.ViewPercentage,
		"view_time":             view_time,
	})
}
